package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;

public class CheckGeneratedTableMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        persistEmployee(em);
        updateEmployeeDepartmentById(em,"Sales",1);
        updateEmployeeDepartmentById(em,"Admin",1);

        em.close();
        emf.close();
    }
    private static void updateEmployeeDepartmentById(EntityManager em,String department,Integer id){
        Employee employee = em.find(Employee.class,id);
        em.getTransaction().begin();
        employee.setDepartment(department);
        em.getTransaction().commit();
        System.err.println("Employee updated: " + JSONObject.toJSONString(employee));
    }
    private static void persistEmployee(EntityManager em){
        Employee employee = new Employee("Joe","IT");
        em.getTransaction().begin();
        em.persist(employee);
        em.getTransaction().commit();
        System.err.println("Employee persisted: " + JSONObject.toJSONString(employee));
    }
    private static void nativeQuery(EntityManager em,String s){
        System.err.println("-------------" + s + "-----------------");
        Query query = em.createNativeQuery(s);
        List list = query.getResultList();
        for (Object o : list) {
            if (o instanceof Object[]) {
                System.err.println(Arrays.toString((Object[])o));
            }else{
                System.err.println(o);
            }
        }
    }
}
